package com.fw.system.web.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.constant.Constant;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.system.web.dao.FwIdentityMapper;
import com.fw.system.web.dao.FwUserMapper;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.ShopIngAgencyForm;
import com.fw.system.web.model.form.ShopIngShangJiaForm;
import com.fw.system.web.service.*;
import com.fw.utils.HttpUtils;
import com.fw.utils.RandomUtils;
import com.fw.utils.StringUtils;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static com.fw.constant.Constant.Identity.*;
import static com.fw.constant.Constant.IsRuleData.*;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-05-10
 */
@Service
@Slf4j
public class FwUserServiceImpl extends ServiceImpl<FwUserMapper, FwUser> implements IFwUserService {

    @Autowired
    private IdXD idXD;
    @Autowired
    private FwUserMapper fwUserMapper;
    @Autowired
    private IFwLogsService logsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private FwUserMapper userMapper;
    @Autowired
    private IFwMoneysService moneysService;
    @Autowired
    private IFwUljoinService uljoinService;
    @Autowired
    private IFwShangjiaService shangjiaService;
    @Autowired
    private IFwRuleDatasService ruleDatasService;
    @Autowired
    private IFwAgentRegionService agentRegionService;
    @Autowired
    private FwIdentityMapper identityMapper;
    @Autowired
    private IFwLockStorageService lockStorageService;
    @Autowired
    private IFwShangjiaReleaseLogService releaseLogService;
    @Autowired
    private IFwCurrencyLogService currencyLogService;

    /**
     * 查询用户
     *
     * @param id 用户ID
     * @return 用户
     */
    @Override
    public FwUser selectFwUserById(String id) {
        return fwUserMapper.selectFwUserById(id);
    }

    /**
     * 查询用户列表
     *
     * @param fwUser 用户
     * @return 用户
     */
    @Override
    public List<FwUser> selectFwUserList(FwUser fwUser) {
        return fwUserMapper.selectFwUserList(fwUser);
    }

    /**
     * 新增用户
     *
     * @param fwUser 用户
     * @return 结果
     */
    @Override
    public int insertFwUser(FwUser fwUser) {
        fwUser.setCreateTime(LocalDateTime.now());
        fwUser.setId(idXD.nextId());
        return fwUserMapper.insertFwUser(fwUser);
    }

    /**
     * 修改用户
     *
     * @param fwUser 用户
     * @return 结果
     */
    @Override
    public int updateFwUser(FwUser fwUser) {
        fwUser.setUpdateTime(LocalDateTime.now());
        return fwUserMapper.updateFwUser(fwUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteFwUserByIds(String[] ids) {
        return fwUserMapper.deleteFwUserByIds(ids);
    }

    /**
     * 删除用户信息
     *
     * @param id 用户ID
     * @return 结果
     */
    @Override
    public int deleteFwUserById(String id) {
        return fwUserMapper.deleteFwUserById(id);
    }


    /**
     * 验证验证码
     *
     * @param phone
     * @param code
     * @return
     */
    public Integer checkCode(String phone, String code) {
        String codes = (String) redisTemplate.opsForValue().get(phone);
        if (StringUtils.isBlank(codes))
            return -1;//请去获取验证码
        if (!codes.equals(code))
            return 0;//验证码错误"
        return 1;
    }


    /**
     * 判断用户是否可多级得消证
     *
     * @param userId
     * @return 可:true 不可:false
     */
    public boolean isDisappearMore(String userId) {
        FwUser fwUser = fwUserMapper.selectFwUserById(userId);
        boolean yy = fwUser.getDisappearIsMore() == 1;
        return yy;
    }

    /**
     * 解绑设备
     *
     * @param fwUser 用户
     * @return 结果
     */
    @Override
    public int imeiNull(FwUser fwUser) {
        fwUser.setUpdateTime(LocalDateTime.now());
        return fwUserMapper.imeiNull(fwUser);
    }

    /**
     * 购买代理
     *
     * @param shopIngAgencyForm
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void ShopIngAgent(ShopIngAgencyForm shopIngAgencyForm) {


        //获取当前登陆者信息
        String userId = shopIngAgencyForm.getUserId();
        //获取所购买代理的价格
        FwRuleDatas ruleDatas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getRuleType, shopIngAgencyForm.getId()));
        BigDecimal ruleCount = ruleDatas.getRuleCount();
       /* //添加购买代理日志
        FwLogShopingAgency fwLogShopingAgency = new FwLogShopingAgency()
                .setId(shopIngAgencyForm.getLogShopIngAgencyId())
                .setUserId(userId)//设置用户id
                .setIdentityId(shopIngAgencyForm.getId())//设置身份id
                .setIsType(Constant.ShopIngLogType.IS_TYPE_ING);//设置审核状态
        logShopingAgencyService.save(fwLogShopingAgency);*/

        /** 新增用户身份  */
        //获取用户现在正在使用的身份
        List<FwUljoin> uljoin = uljoinService.list(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, Constant.IsUsr.IS_USR).eq(FwUljoin::getUserId, userId));
        // 是否重复购买
        long count = uljoin.parallelStream().filter(item -> item.getIdentityId().equals(shopIngAgencyForm.getId())).count();
        if (count!=0L){
            // 重复了
            log.info("{}购买代理重复了~~~",shopIngAgencyForm);
            return;
        }
        //新增日志信息
        logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.ALI_PAY.getModelName(), "购买区域代理", ruleCount.toString());
        //新增用户身份
        FwUljoin fwUljoin = new FwUljoin()
                .setId(idXD.nextId())
                .setIsUse(Constant.IsUsr.IS_USR)
                .setCreateBy(userId)
                .setUserId(userId)
                .setIdentityId(shopIngAgencyForm.getId())
                .setSysCode(shopIngAgencyForm.getId())
                .setCreateTime(LocalDateTime.now());
        //更新用户积分兑换比例
        FwUser user = userMapper.selectById(userId);//获取用户数据
        //判断用户购买的是哪个代理
        if (fwUljoin.getIdentityId().equals(AREA_VIP_ID)) {
            //区县代理,获取区县代理积分兑换比例
            FwRuleDatas datas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.AREA_VIP_INTEGRAL_RELEASE));
            user.setToRelease(datas.getRuleCount());
        } else if (fwUljoin.getIdentityId().equals(CITY_VIP_ID)) {
            //市级代理,获取市级代理积分兑换比例
            FwRuleDatas datas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.CITY_VIP_INTEGRAL_RELEASE));
            user.setToRelease(datas.getRuleCount());
        } else if (fwUljoin.getIdentityId().equals(PROVINCE_VIP_ID)) {
            //省级代理,获取省级代理积分兑换比例
            FwRuleDatas datas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.PROVINCE_INTEGRAL_RELEASE));
            user.setToRelease(datas.getRuleCount());
        }
        userMapper.updateById(user);


        if (uljoin.size() > 0) {
            uljoin.forEach(item -> {
                item.setIsUse(Constant.IsUsr.IS_USR_NO);//设为不使用此身份
                uljoinService.updateById(item);
            });

        }
        uljoinService.save(fwUljoin);
        //获取用户代理区域,判断用户是否已有代理身份
        FwAgentRegion agentRegion = agentRegionService.getOne(Wrappers.<FwAgentRegion>lambdaQuery().eq(FwAgentRegion::getUserId, userId).eq(FwAgentRegion::getIsDefault, Constant.AddrIsDefault.IS_DEFAULT_YES));
        /** 新增用户代理区域 */
        FwAgentRegion entity = new FwAgentRegion()
                .setId(idXD.nextId())
                .setUserId(userId)//设置用户id
                .setIsDefault(Constant.AddrIsDefault.IS_DEFAULT_YES)//设置使用该地址
                .setAgent(shopIngAgencyForm.getId())//设置代理身份
                .setProvince(shopIngAgencyForm.getProvince());//设置区域编码
        if (StringUtils.isNotBlank(shopIngAgencyForm.getArea())) {
            entity.setArea(shopIngAgencyForm.getArea());//设置区域编码
        }
        if (StringUtils.isNotBlank(shopIngAgencyForm.getCity())) {
            entity.setCity(shopIngAgencyForm.getCity());//设置区域编码
        }
        if (agentRegion != null) {
            agentRegion.setIsDefault(Constant.AddrIsDefault.IS_DEFAULT_NO);//设置为不使用该地址
        }
        //新增用户代理区域于数据库
        agentRegionService.save(entity);
        //发放用户购买代理花费的费用的消证给用户
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        moneys.setDisappear(moneys.getDisappear().add(ruleCount));
        moneysService.updateById(moneys);
        //新增日志
        logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), "购买代理", ruleCount.toString());
        // 代理级差逻辑 开启线程池
        ThreadUtil.execute(() -> {
            FwIdentity fwIdentity = identityMapper.selectFwIdentityById(fwUljoin.getIdentityId());
            String info = StringUtils.format("代理提成:", user.getUserName(), fwIdentity.getIdentityName());
            log.info("用户{},购买了{}代理,线程池开始执行!", user.getUserName(), fwIdentity.getIdentityName());
            transferLevelReturn(user.getParentId(), ruleCount, info, userId);
        });
        //todo 返购买代理平台赠送推广的商甲
        FwRuleDatas fwRuleDatas = ruleDatasService.getById(43);
        FwShangjia tuiguang = shangjiaService.getById(2);
        if (tuiguang.getShangjiaQuota().compareTo(fwRuleDatas.getRuleCount()) > 0) {
            //赠送1000 直接锁仓
            FwLockStorage lockStorage = new FwLockStorage();
            lockStorage.setId(idXD.nextId());//id
            lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
            lockStorage.setUserId(userId);//用户编号
            lockStorage.setLockCount(fwRuleDatas.getRuleCount());//锁仓数量
            lockStorage.setNote(fwRuleDatas.getRuleCount().toString());//锁仓总量
            lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
            lockStorage.setReleaseTime(LocalDateTime.now());//兑换时间初始化
            lockStorageService.save(lockStorage);
            tuiguang.setShopIssue(tuiguang.getShopIssue().subtract(fwRuleDatas.getRuleCount()));
            shangjiaService.updateById(tuiguang);
            //新增日志
            FwShangjiaReleaseLog oneLog2 = Builder.of(FwShangjiaReleaseLog::new).with(FwShangjiaReleaseLog::setId, idXD.nextId())
                    .with(FwShangjiaReleaseLog::setCreateTime, LocalDateTime.now())
                    .with(FwShangjiaReleaseLog::setLogType, 4)
                    .with(FwShangjiaReleaseLog::setLogCount, fwRuleDatas.getRuleCount())
                    .with(FwShangjiaReleaseLog::setLogName, "推广商甲")
                    .with(FwShangjiaReleaseLog::setUserId, userId)
                    .with(FwShangjiaReleaseLog::setPhone, userMapper.selectById(userId).getPhone()).build();
            releaseLogService.save(oneLog2);
        }
        //todo 最后调后管增加代理管理员
        //直接进入满1000送商甲阶段
        FwCurrencyLog currencyLog = currencyLogService.getOne(Wrappers.<FwCurrencyLog>lambdaQuery().eq(FwCurrencyLog::getUserId, userId));
        if (currencyLog== null) {
            Builder.of(FwCurrencyLog::new).with(FwCurrencyLog::setId, idXD.nextId()).
                    with(FwCurrencyLog::setCreateTime, LocalDateTime.now()).
                    with(FwCurrencyLog::setLogCount, new BigDecimal(1)).
                    with(FwCurrencyLog::setInfoFrom, 1).with(FwCurrencyLog::setLogName, "满1000消证送商甲阶段").
                    with(FwCurrencyLog::setUserId, userId).with(FwCurrencyLog::setLogType, 2).build().insert();
        }else {
            currencyLog.setLogName("满1000消证送商甲阶段");
            currencyLog.setLogType(2);
            currencyLog.setLogCount(new BigDecimal(1));
            currencyLogService.updateById(currencyLog);
        }
        // 不在受业务管理
        new Thread(()->{ addRuleUserAdmin(userId,shopIngAgencyForm.getProvince(),shopIngAgencyForm.getCity(),shopIngAgencyForm.getArea());}).start();
    }

    @Value("${admin.create.proxy}")
    private String adminCreateProxy;

    public void addRuleUserAdmin(String userId,String province,String city,String area) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("province", province);
        map.put("city", city);
        map.put("area", area);
        try {
            HttpUtil.get(adminCreateProxy,map);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 级差反数据结构
     *
     * @param parentId
     * @param ruleCount
     * @param info      用户购买代理，反积分操作
     */
    private void transferLevelReturn(String parentId, BigDecimal ruleCount, String info, String logSourceUserId) {
        // 防止追溯死 OUTPUT ERROR
        HashSet<String> parentIds = Sets.newHashSet();
        levelReturn(parentId, ruleCount, info, null, Boolean.TRUE, parentIds, logSourceUserId);
    }

    /**
     * 级差反 （数据）
     *
     * @param parentId  父ID
     * @param ruleCount 总金额
     * @param info      // 返利来源信息
     */
    private void levelReturn(String parentId, BigDecimal ruleCount, String info, Map<String, FwIdentity> topLevel, boolean isOne, HashSet<String> parentIds, String logSourceUserId) {
        // buffPool ruleData 缓冲规则池，查看返利比例
        Map<String, BigDecimal> ruleData = initBuffPool();
        // 级差流开始。
        // 查看当前什么身份？
        Map<String, FwIdentity> mapId = findParent(parentId, parentIds);

        // 如果这个身份是null 那么就断档。
        if (Objects.isNull(mapId)) {
            log.info("代理购买已经断档,不在进行返利!{}", info);
            return;
        }
        String parentLevelId = mapId.keySet().stream().findAny().get();
        FwIdentity identity = mapId.values().stream().findAny().get();

        // 拿到N上级身份 开始返利,不过需要知道他下级是什么？
        // 如果不是第一次返利的话
        FwIdentity topDdentity = null;
        // 那就将这个代理的上级抽成比拿到, 进行 - 法操作，最终算出来当前代理拿多少费用。
        if (!isOne) {
            topDdentity = topLevel.values().stream().findAny().get();
        }
        // 如果当前级都是代理,那么往后 直返回固定的返利比 %5,否则拿出当前代理的比例
        BigDecimal fixed = NumberUtil.add(0.00);
        if (isProxy(identity) && (fixed = (ruleData.get(identity.getId())).subtract(Objects.isNull(topDdentity) ? NumberUtil.add(0D) : ruleData.get(topDdentity.getId()))).intValue() != 0) {
            // 如果 fixed !=0 说明有一个代理，接下来全部根据这个代理抽成比进行计算 接下来遇到的代理固定 %5,只能反在一个代理才是%5 自始结束即可
            // 即将结束，再反一级即可，找到他上溯的代理 给5%，找不到就流失平台。
            userAddIntegralProxy(ruleCount, info, parentLevelId, identity, fixed, parentIds);
        } else {
            //非固定流程开始
            if (isOne) {
                // 第一次的话，就直接拿当前身份比例开始算积分了
                BigDecimal proportionThis = ruleData.get(identity.getId());
                userAddIntegral(ruleCount, info, mapId, parentLevelId, identity, proportionThis, parentIds, logSourceUserId);
            } else {
                // 不是第一次的话
                // 1.1 同级别 抽下级 得到积分的 百分之20 ?
                if (Integer.parseInt(identity.getId()) == Integer.parseInt(topDdentity.getId())) {
                    // 跳过 继续 回溯
                    levelReturn(userMapper.selectById(parentLevelId).getParentId(), ruleCount, info, mapId, Boolean.FALSE, parentIds, logSourceUserId);
                }
                // 1.2 非同级别
                // 1.2.1 我等级比下级等级高的 自己抽成比 - 下级抽成比
                if (Integer.parseInt(identity.getId()) > Integer.parseInt(topDdentity.getId())) {
                    BigDecimal proportionThis = ruleData.get(identity.getId()).subtract(ruleData.get(topDdentity.getId()));
                    userAddIntegral(ruleCount, info, mapId, parentLevelId, identity, proportionThis, parentIds, logSourceUserId);
                }
                // 1.2.2 等级低的 额外逻辑，topLevel 需要记录上次的抽成的身份
                if (Integer.parseInt(identity.getId()) < Integer.parseInt(topDdentity.getId())) {
                    // 跳过 继续 回溯
                    levelReturn(userMapper.selectById(parentLevelId).getParentId(), ruleCount, info, topLevel, Boolean.FALSE, parentIds, logSourceUserId);
                }
            }
        }
    }


    /**
     * 废弃
     *
     * @param parentId
     * @param ruleCount
     * @param info
     */
    @Deprecated
    private void transferLevelReturnDeprecated(String parentId, BigDecimal ruleCount, String info) {
        // 防止追溯死 OUTPUT ERROR
        HashSet<String> parentIds = Sets.newHashSet();
        levelReturnDeprecated(parentId, ruleCount, info, Boolean.FALSE, NumberUtil.add(0D), null, Boolean.TRUE, parentIds);
    }

    /**
     * 废弃
     * 级差反 （数据）
     *
     * @param parentId   父ID
     * @param ruleCount  总金额
     * @param info       // 返利来源信息
     * @param isFixed    是否固定比例
     * @param proportion 如果是固定比例，就一致用这个即可
     */
    @Deprecated
    private void levelReturnDeprecated(String parentId, BigDecimal ruleCount, String info, boolean isFixed, BigDecimal proportion, Map<String, FwIdentity> topLevel, boolean isOne, HashSet<String> parentIds) {
        // buffPool ruleData 缓冲规则池，查看返利比例
        Map<String, BigDecimal> ruleData = initBuffPool();
        // 级差流开始。
        // 查看当前什么身份？
        Map<String, FwIdentity> mapId = findParent(parentId, parentIds);

        // 如果这个身份是null 那么就断档。
        if (Objects.isNull(mapId) || ruleCount.compareTo(NumberUtil.add(0D)) <= -1) {
            log.info("代理购买已经断档,不在进行返利!{}", info);
            return;
        }
        String parentLevelId = mapId.keySet().stream().findAny().get();
        FwIdentity identity = mapId.values().stream().findAny().get();

        // 拿到N上级身份 开始返利,不过需要知道他下级是什么？
        // 如果不是第一次返利的话
        FwIdentity topDdentity = null;
        // 那就将这个代理的上级抽成比拿到, 进行 - 法操作，最终算出来当前代理拿多少费用。
        if (!isOne) {
            topDdentity = topLevel.values().stream().findAny().get();
        }
        // 如果当前级都是代理,那么往后全部都是固定的返利比,否则拿出当前代理的比例
        BigDecimal fixed = NumberUtil.add(0.00);
        if (isFixed || (isProxy(identity) && (fixed = isFixed ? proportion : ruleData.get(identity.getId())).subtract(Objects.isNull(topDdentity) ? NumberUtil.add(0D) : ruleData.get(topDdentity.getId())).intValue() != 0)) {
            // 如果 fixed !=0 说明有一个代理，接下来全部根据这个代理抽成比进行计算
            userAddIntegralDeprecated(ruleCount, info, mapId, parentLevelId, identity, fixed, Boolean.TRUE, ruleData.get(identity.getId()), parentIds);
        } else {
            //非固定流程开始
            if (isOne) {
                // 第一次的话，就直接拿当前身份比例开始算积分了
                BigDecimal proportionThis = ruleData.get(identity.getId());
                userAddIntegralDeprecated(ruleCount, info, mapId, parentLevelId, identity, proportionThis, Boolean.FALSE, proportionThis, parentIds);
            } else {
                // 不是第一次的话
                // 1.1 同级别 抽下级 得到积分的 百分之20 ?
                if (Integer.parseInt(identity.getId()) == Integer.parseInt(topDdentity.getId())) {
                    //
                }
                // 1.2 非同级别
                // 1.2.1 我等级比下级等级高的 自己抽成比 - 下级抽成比
                if (Integer.parseInt(identity.getId()) > Integer.parseInt(topDdentity.getId())) {
                    BigDecimal proportionThis = ruleData.get(identity.getId()).subtract(ruleData.get(topDdentity.getId()));
                    userAddIntegralDeprecated(ruleCount, info, mapId, parentLevelId, identity, proportionThis, Boolean.FALSE, ruleData.get(identity.getId()), parentIds);
                }
                // 1.2.2 等级低的
                if (Integer.parseInt(identity.getId()) < Integer.parseInt(topDdentity.getId())) {
                    //
                }
            }
        }
    }

    /**
     * 废弃
     *
     * @param ruleCount
     * @param info
     * @param mapId
     * @param parentLevelId
     * @param identity
     * @param proportionThis
     * @param isFixed
     * @param proxyFixed
     * @param parentIds
     */
    @Deprecated
    private void userAddIntegralDeprecated(BigDecimal ruleCount, String info, Map<String, FwIdentity> mapId, String parentLevelId, FwIdentity identity, BigDecimal proportionThis, Boolean isFixed, BigDecimal proxyFixed, HashSet<String> parentIds) {
        BigDecimal integral = RandomUtils.mathNumber(proportionThis, ruleCount);
        FwMoneys fwMoneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, parentLevelId));
        fwMoneys.setIntegral(fwMoneys.getIntegral().add(integral)).updateById();
        logsService.saveLogs(parentLevelId, parentLevelId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), info.concat(integral.toString()), integral.toString());
        log.info("用户购买代理成功,此级别为{},分成比例全部固化好.此轮比例为{},分积分为{}", identity.getIdentityName(), proportionThis, integral);
        levelReturnDeprecated(userMapper.selectById(parentLevelId).getParentId(), integral, info, isFixed, proxyFixed, mapId, Boolean.FALSE, parentIds);
    }

    /**
     * 普通用户级差反
     *
     * @param ruleCount       购买代理总金额  原始金额开始发放
     * @param info            购买信息详情内容
     * @param mapId           当前用户等级
     * @param parentLevelId   当前用户 编号
     * @param identity        当前用户身份
     * @param proportionThis  当前的返利比是？
     * @param parentIds       去除重复夫节点集合
     * @param logSourceUserId 日志原始人用户编号
     */
    private void userAddIntegral(BigDecimal ruleCount, String info, Map<String, FwIdentity> mapId, String parentLevelId, FwIdentity identity, BigDecimal proportionThis, HashSet<String> parentIds, String logSourceUserId) {
        BigDecimal integral = RandomUtils.mathNumber(proportionThis, ruleCount);
        FwMoneys fwMoneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, parentLevelId));
        fwMoneys.setIntegral(fwMoneys.getIntegral().add(integral)).updateById();
        logsService.saveLogs(logSourceUserId, parentLevelId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), info.concat(integral.toString()), integral.toString());
        log.info("用户购买代理成功,此级别为{},分成比例全部固化好.此轮比例为{},分积分为{}", identity.getIdentityName(), proportionThis, integral);
        levelReturn(userMapper.selectById(parentLevelId).getParentId(), ruleCount, info, mapId, Boolean.FALSE, parentIds, logSourceUserId);
    }

    /**
     * 代理 反
     *
     * @param ruleCount      购买代理总金额  原始金额开始发放
     * @param info           购买信息详情内容
     * @param parentLevelId  当前用户 编号
     * @param identity       当前用户身份
     * @param proportionThis 当前的返利比是？
     * @param parentIds      去除重复夫节点集合
     */
    private void userAddIntegralProxy(BigDecimal ruleCount, String info, String parentLevelId, FwIdentity identity, BigDecimal proportionThis, HashSet<String> parentIds) {
        BigDecimal integral = RandomUtils.mathNumber(proportionThis, ruleCount);
        FwMoneys fwMoneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, parentLevelId));
        fwMoneys.setIntegral(fwMoneys.getIntegral().add(integral)).updateById();
        logsService.saveLogs(parentLevelId, parentLevelId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), info.concat(integral.toString()), integral.toString());
        log.info("用户购买代理成功,此级别为{},分成比例全部固化好.此轮比例为{},分积分为{}", identity.getIdentityName(), proportionThis, integral);
        //levelReturn(userService.getById(parentLevelId).getParentId(), ruleCount, info, isFixed, proxyFixed, mapId, Boolean.FALSE,parentIds);
        // 找到这哥们的无限代上级是否有代理,有的话就直接给 %5
        String parentId = userMapper.selectById(parentLevelId).getParentId();
        Map<String, FwIdentity> parentProxyMap = null;
        if ((parentProxyMap = findParentProxy(parentId, parentIds)) != null) {
            // 直接给 %5 即可
            String parentIdProxy = parentProxyMap.keySet().stream().findAny().get();
            FwIdentity parentIdenProxy = parentProxyMap.values().stream().findAny().get();
            integral = RandomUtils.mathNumber(NumberUtil.add(5D), ruleCount);
            fwMoneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, parentIdProxy));
            fwMoneys.setIntegral(fwMoneys.getIntegral().add(integral)).updateById();
            logsService.saveLogs(parentIdProxy, parentIdProxy, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), info.concat(integral.toString()), integral.toString());
            log.info("用户购买代理成功,此级别为{},分成比例全部固化好.此轮比例为{},分积分为{}", parentIdenProxy.getIdentityName(), "5", integral);

        }
    }

    /**
     * @param parentId  上级编号
     * @param parentIds 防止无限回溯
     * @return
     */
    private Map<String, FwIdentity> findParent(String parentId, Set<String> parentIds) {
        if (StringUtils.isNotBlank(parentId) && parentIds.add(parentId)) {
            // 查找的路上
            FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, parentId).eq(FwUljoin::getIsUse, Constant.IsUsr.IS_USR));
            FwIdentity identity = null;
            if (Objects.nonNull(uljoin) && Objects.nonNull(identity = identityMapper.selectFwIdentityById(uljoin.getIdentityId()))) {
                HashMap<String, FwIdentity> converIdMap = Maps.newHashMap();
                converIdMap.put(parentId, identity);
                return converIdMap;

            }


            // 回溯查找
            return findParent(Optional.<FwUser>of(getById(parentId)).orElse(new FwUser()).getParentId(), parentIds);
        }
        return null;
    }


    /**
     * 回溯查找代理
     *
     * @param parentId  上级编号
     * @param parentIds 防止无限回溯
     * @return
     */
    private Map<String, FwIdentity> findParentProxy(String parentId, Set<String> parentIds) {
        if (parentIds.add(parentId)) {
            // 查找的路上
            FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, parentId).eq(FwUljoin::getIsUse, Constant.IsUsr.IS_USR));
            FwIdentity identity = null;
            if (Objects.nonNull(uljoin) && Objects.nonNull(identity = identityMapper.selectFwIdentityById(uljoin.getIdentityId())) && isProxy(identity)) {
                HashMap<String, FwIdentity> converIdMap = Maps.newHashMap();
                converIdMap.put(parentId, identity);
                return converIdMap;

            }


            // 回溯查找代理
            return findParentProxy(getById(parentId).getParentId(), parentIds);
        }
        return null;
    }

    private boolean isProxy(FwIdentity identity) {
        return identity.getId().equals(AREA_VIP_ID) || identity.getId().equals(CITY_VIP_ID) || identity.getId().equals(PROVINCE_VIP_ID);
    }


    /**
     * 级差 根据规则缓冲代理比例
     *
     * @return
     */
    private Map<String, BigDecimal> initBuffPool() {
        // key = 代理身份编号 ; val = 比例;
        HashMap<String, BigDecimal> ruleDataMaps = Maps.newHashMap();
        ruleDataMaps.put("1", ruleDatasService.getById(GO_PROXY_LEVEL_VIP).getRuleCount());
        ruleDataMaps.put("2", ruleDatasService.getById(GO_PROXY_LEVEL_ONE_START).getRuleCount());
        ruleDataMaps.put("3", ruleDatasService.getById(GO_PROXY_LEVEL_TOW_START).getRuleCount());
        ruleDataMaps.put("4", ruleDatasService.getById(GO_PROXY_LEVEL_THREE_START).getRuleCount());
        ruleDataMaps.put("5", ruleDatasService.getById(GO_PROXY_LEVEL_AREA_START).getRuleCount());
        ruleDataMaps.put("6", ruleDatasService.getById(GO_PROXY_LEVEL_CITY_START).getRuleCount());
        ruleDataMaps.put("7", ruleDatasService.getById(GO_PROXY_LEVEL_PROVINCE_START).getRuleCount());
        return ruleDataMaps;
    }


    /**
     * 认购原始商甲
     *
     * @param shopIngShangJiaForm
     * @return
     */
    public void ShopIngShangJia(ShopIngShangJiaForm shopIngShangJiaForm) {

        //获取原始商甲剩余额度
        FwShangjia shangjia = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.ORIGINAL_ID));
        //发放商甲
        //减少原始商甲额度
        BigDecimal multiply = shangjia.getShopIssue().subtract(shopIngShangJiaForm.getCount());
        shangjia.setShopIssue(multiply);
        shangjia.setUpdateBy(shopIngShangJiaForm.getUserId());
        shangjia.setUpdateTime(LocalDateTime.now());
        shangjiaService.updateById(shangjia);
        //给用户增加商甲
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, shopIngShangJiaForm.getUserId()));
        BigDecimal shangJia = moneys.getShangJia();
        BigDecimal add = shangJia.add(shopIngShangJiaForm.getCount());
        moneys.setShangJia(add);
        moneysService.updateById(moneys);
        //调用锁仓
        moneysService.extracted(moneys.getUserId(), moneysService.getById(moneys.getUserId()));
        //新增商甲收入日志
        logsService.saveLogs(shopIngShangJiaForm.getUserId(), shopIngShangJiaForm.getUserId(), LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "认购原始商甲", shopIngShangJiaForm.getCount().toString());
        //新增支付宝支出日志
        logsService.saveLogs(shopIngShangJiaForm.getUserId(), shopIngShangJiaForm.getUserId(), LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.ALI_PAY.getModelName(), "认购原始商甲", shopIngShangJiaForm.getMoney().toString());

    }


    /**
     * 绑定上级后续逻辑
     */
    public void bindingParent(FwUser user) {
        //获取其上级数据
        FwUser parentUser = fwUserMapper.selectOne(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId, user.getParentId()));
        if (parentUser != null) {
            //查询下级是vip的数量
            int count = uljoinService.countVip(parentUser.getId());
            //获取其上级身份数据
            FwUljoin parentUljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, parentUser.getId()).eq(FwUljoin::getIsUse, Constant.IsUsr.IS_USR));
            //获取升为1星的直推人数
            FwRuleDatas one1 = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.Recommend.ONE_VIP_COUNT));
            Integer ruleCount1 = one1.getRuleCount().intValue();
            FwRuleDatas one2 = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.Recommend.TWO_VIP_COUNT));
            Integer ruleCount2 = one2.getRuleCount().intValue();
            FwRuleDatas one3 = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.Recommend.THREE_VIP_COUNT));
            Integer ruleCount3 = one3.getRuleCount().intValue();
            //判空
            if (parentUljoin != null) {
                boolean flag = false;
                //查看星级表示
                FwCurrencyLog currencyLog = currencyLogService.getOne(Wrappers.<FwCurrencyLog>lambdaQuery().eq(FwCurrencyLog::getUserId, parentUser.getId()).eq(FwCurrencyLog::getLogType, 5));
                if (count >= ruleCount1 && count < ruleCount2) {
                    //如果用户已经是一星
                    if (Integer.valueOf(parentUljoin.getSysCode()) < 2)
                        flag = true;
                    oneStart(currencyLog, parentUser.getId(), flag);
                }
                if (count >= ruleCount2 && count < ruleCount3) {
                    //如果二星
                    if (Integer.valueOf(parentUljoin.getSysCode()) < 3)
                        flag = true;
                    otwoStart(currencyLog, parentUser.getId(), flag);
                }
                if (count >= ruleCount3) {
                    if (Integer.valueOf(parentUljoin.getSysCode()) < 4)
                        flag = true;
                    threeStart(currencyLog, parentUser.getId(), flag, count);
                }

            }
        }
    }


    //升级一星方法
    public void oneStart(FwCurrencyLog currencyLog, String userId, boolean flag) {
        if (currencyLog == null) {
            //打入一星标识
            currencyLog = Builder.of(FwCurrencyLog::new).with(FwCurrencyLog::setId, idXD.nextId()).
                    with(FwCurrencyLog::setCreateTime, LocalDateTime.now()).
                    with(FwCurrencyLog::setLogCount, new BigDecimal(1)).
                    with(FwCurrencyLog::setInfoFrom, 1).with(FwCurrencyLog::setLogName, "一星阶段标识").
                    with(FwCurrencyLog::setUserId, userId).with(FwCurrencyLog::setLogType, 5).build();
            currencyLogService.save(currencyLog);
        }
        if (flag) {
            FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, userId).eq(FwUljoin::getIsUse, 1));
            uljoin.setIsUse(Constant.IsUsr.IS_USR_NO);
            uljoinService.updateById(uljoin);
            //新增身份
            FwUljoin fwUljoin = new FwUljoin();
            fwUljoin.setCreateTime(LocalDateTime.now());
            fwUljoin.setId(idXD.nextId());
            fwUljoin.setIdentityId(Constant.Identity.ONE_VIP_ID);
            fwUljoin.setIsUse(Constant.IsUsr.IS_USR);
            //系统平台身份的标识码_反三范式设计
            fwUljoin.setSysCode(Constant.Identity.ONE_VIP_ID);
            fwUljoin.setUserId(uljoin.getUserId());
            uljoinService.save(fwUljoin);
            //更新用户积分兑换比例
            userMapper.updateById(userMapper.selectById(userId).setToRelease(ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.ONE_VIP_ONE_INTEGRAL_RELEASE)).getRuleCount()));
            FwShangjia shangjia = shangjiaService.getById("2");
            FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
            FwRuleDatas sendShangJia = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.ONE_STAR_SHANG_JIA_ID));
            if (shangjia.getShopIssue().compareTo(sendShangJia.getRuleCount()) > -1) {
                moneysService.updateById(moneys.setShangJia(moneys.getShangJia().add(sendShangJia.getRuleCount())));
            }
            //todo 扣去推广商甲池的商甲
            shangjiaService.updateById(shangjia.setShopIssue(shangjia.getShopIssue().subtract(sendShangJia.getRuleCount())));
            //调用锁仓
            moneysService.extracted(userId, moneys);
            //增加释放明细
            FwShangjiaReleaseLog oneLog = Builder.of(FwShangjiaReleaseLog::new).with(FwShangjiaReleaseLog::setId, idXD.nextId())
                    .with(FwShangjiaReleaseLog::setCreateTime, LocalDateTime.now())
                    .with(FwShangjiaReleaseLog::setLogType, 4)
                    .with(FwShangjiaReleaseLog::setLogCount, sendShangJia.getRuleCount())
                    .with(FwShangjiaReleaseLog::setLogName, "成为1星奖励")
                    .with(FwShangjiaReleaseLog::setUserId, userId)
                    .with(FwShangjiaReleaseLog::setPhone, userMapper.selectById(userId).getPhone()).build();
            releaseLogService.save(oneLog);

            //更改为二星阶段标识
            currencyLog.setLogCount(new BigDecimal(2));
            currencyLog.setLogName("二星阶段标识");
            currencyLogService.updateById(currencyLog);
        }


    }

    //升级二星方法
    public void otwoStart(FwCurrencyLog currencyLog, String userId, boolean flag) {
        if (currencyLog == null) {
            //打入一星标识
            currencyLog = Builder.of(FwCurrencyLog::new).with(FwCurrencyLog::setId, idXD.nextId()).
                    with(FwCurrencyLog::setCreateTime, LocalDateTime.now()).
                    with(FwCurrencyLog::setLogCount, new BigDecimal(2)).
                    with(FwCurrencyLog::setInfoFrom, 1).with(FwCurrencyLog::setLogName, "二星阶段标识").
                    with(FwCurrencyLog::setUserId, userId).with(FwCurrencyLog::setLogType, 5).build();
            currencyLogService.save(currencyLog);
        }
        if (flag) {
            FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, userId).eq(FwUljoin::getIsUse, 1));
            uljoin.setIsUse(Constant.IsUsr.IS_USR_NO);
            uljoinService.updateById(uljoin);
            //新增身份
            FwUljoin fwUljoin = new FwUljoin();
            fwUljoin.setCreateTime(LocalDateTime.now());
            fwUljoin.setId(idXD.nextId());
            fwUljoin.setIdentityId(Constant.Identity.TWO_VIP_ID);
            fwUljoin.setIsUse(Constant.IsUsr.IS_USR);
            //系统平台身份的标识码_反三范式设计
            fwUljoin.setSysCode(Constant.Identity.TWO_VIP_ID);
            fwUljoin.setUserId(uljoin.getUserId());
            uljoinService.save(fwUljoin);
            //更新用户积分兑换比例
            userMapper.updateById(userMapper.selectById(userId).setToRelease(ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.TWO_VIP_INTEGRAL_RELEASE)).getRuleCount()));
            FwShangjia shangjia = shangjiaService.getById("2");
            FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
            FwRuleDatas sendShangJia = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.TWO_STAR_SHANG_JIA_ID));
            if (shangjia.getShopIssue().compareTo(sendShangJia.getRuleCount()) > 0) {
                moneysService.updateById(moneys.setShangJia(moneys.getShangJia().add(sendShangJia.getRuleCount())));
            }
            //todo 扣去推广商甲池的商甲
            shangjiaService.updateById(shangjia.setShopIssue(shangjia.getShopIssue().subtract(sendShangJia.getRuleCount())));
            //调用锁仓
            moneysService.extracted(userId, moneys);
            //增加释放明细
            FwShangjiaReleaseLog oneLog = Builder.of(FwShangjiaReleaseLog::new).with(FwShangjiaReleaseLog::setId, idXD.nextId())
                    .with(FwShangjiaReleaseLog::setCreateTime, LocalDateTime.now())
                    .with(FwShangjiaReleaseLog::setLogType, 4)
                    .with(FwShangjiaReleaseLog::setLogCount, sendShangJia.getRuleCount())
                    .with(FwShangjiaReleaseLog::setLogName, "成为2星奖励")
                    .with(FwShangjiaReleaseLog::setUserId, userId)
                    .with(FwShangjiaReleaseLog::setPhone, userMapper.selectById(userId).getPhone()).build();
            releaseLogService.save(oneLog);

            //更改为二星阶段标识
            currencyLog.setLogCount(new BigDecimal(3));
            currencyLog.setLogName("三星阶段标识");
            currencyLogService.updateById(currencyLog);
        }

    }

    //升级三星方法
    public void threeStart(FwCurrencyLog currencyLog, String userId, boolean flag, int count) {
        if (currencyLog == null) {
            //打入一星标识
            currencyLog = Builder.of(FwCurrencyLog::new).with(FwCurrencyLog::setId, idXD.nextId()).
                    with(FwCurrencyLog::setCreateTime, LocalDateTime.now()).
                    with(FwCurrencyLog::setLogCount, new BigDecimal(3)).
                    with(FwCurrencyLog::setInfoFrom, 1).with(FwCurrencyLog::setLogName, "三星阶段标识").
                    with(FwCurrencyLog::setUserId, userId).with(FwCurrencyLog::setLogType, 5).build();
            currencyLogService.save(currencyLog);
        }
        if (currencyLog.getLogCount().compareTo(new BigDecimal(3)) <= 0) {
            //走三星奖励
            if (flag) {
                FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, userId).eq(FwUljoin::getIsUse, 1));
                uljoin.setIsUse(Constant.IsUsr.IS_USR_NO);
                uljoinService.updateById(uljoin);
                //新增身份
                FwUljoin fwUljoin = new FwUljoin();
                fwUljoin.setCreateTime(LocalDateTime.now());
                fwUljoin.setId(idXD.nextId());
                fwUljoin.setIdentityId(Constant.Identity.THREE_VIP_ID);
                fwUljoin.setIsUse(Constant.IsUsr.IS_USR);
                //系统平台身份的标识码_反三范式设计
                fwUljoin.setSysCode(Constant.Identity.THREE_VIP_ID);
                fwUljoin.setUserId(uljoin.getUserId());
                uljoinService.save(fwUljoin);
                //更新用户积分兑换比例
                userMapper.updateById(userMapper.selectById(userId).setToRelease(ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.THREE_VIP_INTEGRAL_RELEASE)).getRuleCount()));
                FwShangjia shangjia = shangjiaService.getById("2");
                FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
                FwRuleDatas sendShangJia = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.THREE_STAR_SHANG_JIA_ID));
                if (shangjia.getShopIssue().compareTo(sendShangJia.getRuleCount()) > 0) {
                    moneysService.updateById(moneys.setShangJia(moneys.getShangJia().add(sendShangJia.getRuleCount())));
                }
                //todo 扣去推广商甲池的商甲
                shangjiaService.updateById(shangjia.setShopIssue(shangjia.getShopIssue().subtract(sendShangJia.getRuleCount())));
                //调用锁仓
                moneysService.extracted(userId, moneys);
                //增加释放明细
                FwShangjiaReleaseLog oneLog = Builder.of(FwShangjiaReleaseLog::new).with(FwShangjiaReleaseLog::setId, idXD.nextId())
                        .with(FwShangjiaReleaseLog::setCreateTime, LocalDateTime.now())
                        .with(FwShangjiaReleaseLog::setLogType, 4)
                        .with(FwShangjiaReleaseLog::setLogCount, sendShangJia.getRuleCount())
                        .with(FwShangjiaReleaseLog::setLogName, "成为3星奖励")
                        .with(FwShangjiaReleaseLog::setUserId, userId)
                        .with(FwShangjiaReleaseLog::setPhone, userMapper.selectById(userId).getPhone()).build();
                releaseLogService.save(oneLog);
                FwRuleDatas one3 = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.Recommend.THREE_VIP_COUNT));
                Integer ruleCount3 = one3.getRuleCount().intValue();
                if (count > ruleCount3) {
                    int m = count - ruleCount3;
                    for (int i = 0; i < m; i++) {
                        if (shangjia.getShopIssue().compareTo(sendShangJia.getRuleCount()) > 0) {
                            moneysService.updateById(moneys.setShangJia(moneys.getShangJia().add(new BigDecimal(2))));
                        }
                        //todo 扣去推广商甲池的商甲
                        shangjiaService.updateById(shangjia.setShopIssue(shangjia.getShopIssue().subtract(sendShangJia.getRuleCount())));
                        //调用锁仓
                        moneysService.extracted(userId, moneys);
                        //增加释放明细
                        FwShangjiaReleaseLog oneLog1 = Builder.of(FwShangjiaReleaseLog::new).with(FwShangjiaReleaseLog::setId, idXD.nextId())
                                .with(FwShangjiaReleaseLog::setCreateTime, LocalDateTime.now())
                                .with(FwShangjiaReleaseLog::setLogType, 4)
                                .with(FwShangjiaReleaseLog::setLogCount, new BigDecimal(2))
                                .with(FwShangjiaReleaseLog::setLogName, "成为3后星奖励")
                                .with(FwShangjiaReleaseLog::setUserId, userId)
                                .with(FwShangjiaReleaseLog::setPhone, userMapper.selectById(userId).getPhone()).build();
                        releaseLogService.save(oneLog1);
                    }
                }

                //更改为二星阶段标识
                currencyLog.setLogCount(new BigDecimal(4));
                currencyLog.setLogName("三星后阶段标识");
                currencyLog.setInfoFrom(count);
                currencyLogService.updateById(currencyLog);
            }
        } else {
            //走三星后的
            FwRuleDatas one3 = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.Recommend.THREE_VIP_COUNT));
            Integer ruleCount3 = one3.getRuleCount().intValue();
            if (currencyLog.getInfoFrom() < count) {
                FwShangjia shangjia = shangjiaService.getById("2");
                FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
                BigDecimal ruleCount = new BigDecimal(2);

                int m = count - currencyLog.getInfoFrom();
                for (int i = 0; i < m; i++) {
                    if (shangjia.getShopIssue().compareTo(ruleCount) > 0) {
                        moneysService.updateById(moneys.setShangJia(moneys.getShangJia().add(ruleCount)));
                    }
                    //todo 扣去推广商甲池的商甲
                    shangjiaService.updateById(shangjia.setShopIssue(shangjia.getShopIssue().subtract(ruleCount)));
                    //调用锁仓
                    moneysService.extracted(userId, moneys);
                    //增加释放明细
                    FwShangjiaReleaseLog oneLog1 = Builder.of(FwShangjiaReleaseLog::new).with(FwShangjiaReleaseLog::setId, idXD.nextId())
                            .with(FwShangjiaReleaseLog::setCreateTime, LocalDateTime.now())
                            .with(FwShangjiaReleaseLog::setLogType, 4)
                            .with(FwShangjiaReleaseLog::setLogCount, ruleCount)
                            .with(FwShangjiaReleaseLog::setLogName, "成为3后星奖励")
                            .with(FwShangjiaReleaseLog::setUserId, userId)
                            .with(FwShangjiaReleaseLog::setPhone, userMapper.selectById(userId).getPhone()).build();
                    releaseLogService.save(oneLog1);

                }
                //更改为二星阶段标识
                currencyLog.setInfoFrom(count);
                currencyLog.setLogName("三星后阶段标识");
                currencyLogService.updateById(currencyLog);
            }

        }

    }

    @Autowired
    private IFwUserService userService;
    /**
     * 查询120天未登录的用户,将其删除
     */
    public void delUser() {
        //获取120天前的时间
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(120);
        List<FwUser> users = fwUserMapper.selectList(Wrappers.<FwUser>lambdaQuery().lt(FwUser::getUpdateTime, localDateTime));
        if (!users.isEmpty()) {
            // 如果不为空 干掉，干掉！ 用户手机号全部 多加 两位 **
            for (FwUser user : users) {
                user.setPhone(user.getPhone().concat("-disable"));
                // TODO 商甲逻辑开始
            }
        }
        userService.updateBatchById(users);


    }

    @Override
    @Deprecated
    public void exe() {
        // 代理级差逻辑 开启线程池
        ThreadUtil.execute(() -> {
            FwIdentity fwIdentity = identityMapper.selectFwIdentityById("5");
            String info = StringUtils.format("您的下级用户{},购买了{}代理,您获取返利:", "cvergbt", fwIdentity.getIdentityName());
            log.info("用户{},购买了{}代理,线程池开始执行!", "cvergbt", fwIdentity.getIdentityName());
            transferLevelReturn("1427496407530491904", NumberUtil.add(40000D), info, "1427501417467236352");
        });
    }

}
